2015-04-04 99 views
0

对于exercice,我所著的C++ 有点类不能被强制转换为其他类型比一般的参数T歧义与COUT <<和施放C++

template <class T> 
class pure 
{ 
public: 

pure(T const& attr) 
{ 
    this->attr = attr; 
} 

~pure() 
{ 
} 

T& operator=(T const& attr) 
{ 
    return attr; 
} 

operator T() 
{ 
    return attr; 
} 

template<typename U> 
operator U() = delete; 

private: 
T attr; 
}; 

这里是主要的:

int main() 
{ 
pure<int> i = 15; 

    //This won't compile, like I wanted 
    //All the casts to other types than int won't compile 
cout << (short)i; 

    //BUT when I'm using mye pure object without a cast, I get a lot of ambiguities errors 
    cout << i; 

system("PAUSE"); 
return 0; 
} 

那么,为什么第二个cout不起作用?这应该是工作,因为我删除了所有其他可能的转换比int。感谢帮助。回到这可能有助于了解:Prevent an object to be casted to any but one type C++

+1

[删除功能参与重载解析](http://stackoverflow.com/questions/14085620/why-do-c11-deleted-functions-participate -in-超负荷分辨率)。 – chris 2015-04-04 19:28:08

回答

3

如果您为pure<T>超载<<运算符,则您的代码正常工作。

#include <iostream> 

template <class T> 
class pure { 
    T attr; 

public: 
    pure(T const& attr) { 
     this->attr = attr; 
    } 

    T& operator=(T const& attr) { 
     return attr; 
    } 

    operator T() { 
     return attr; 
    } 

    template<typename U> 
    operator U() = delete; 
}; 

template<typename T> 
std::ostream& operator<<(std::ostream& os, pure<T> p) { 
    os << static_cast<T>(p); 
    return os; 
} 

int main() 
{ 
    using namespace std; 
    pure<int> i = 15; 

    //This won't compile, like I wanted 
    //All the casts to other types than int won't compile 
    cout << static_cast<short>(i); 

    //Now works fine 
    cout << i; 

    return 0; 
} 
+0

相当不错的答案,但我不想为了解决所有操作员的歧义而写大量的操作员!有一种方法更容易吗?是否存在一个“通配符”运算符为每个运算符做静态转换? – 2015-04-04 19:39:23

+0

不幸的是,没有通配符运算符。你可以用宏来实现你感兴趣的操作符。 – 2015-04-04 19:50:55

2

Why do C++11-deleted functions participate in overload resolution?理解为什么

cout << i << endl; 

不起作用。

解决方法:

  1. 提供一个适当operator<<()过载。

  2. 删除显式删除的转换运算符。

下面的代码工作:

#include <iostream> 

template <typename T> 
class pure 
{ 
    public: 
     operator T() 
     { 
     return 0; 
     } 

}; 

int main() 
{ 
    pure<int> p; 
    std::cout << p << std::endl; 
} 
+1

是的,但纯粹的目标是防止将纯对象转换为另一种类型而不是T。你正在破坏所有我想要的在开始时做。 http://stackoverflow.com/questions/29431972/prevent-an-object-to-be-casted-to-any-but-one-type-c您还删除了我的糖初始化程序。 – 2015-04-04 19:51:23

+0

@ Marc-AntoineJacob:对,所以选项#1是您唯一的解决方案。 – 2015-04-04 19:56:00

+0

但是,这是愚蠢的!我明确删除了所有其他运营商!为什么有歧义?! – 2015-04-04 19:57:26

相关问题