【发布时间】:2017-01-22 16:17:21
【问题描述】:
我想通过特质专业化来做以下事情。
Array Aa = Scalar in_a将使用overload I。Array Aa = Array Bb将使用overload II。
在下面的代码中,overload II 永远不会被使用。
有人提到T1不能在overload II中推导出来。
如何解决?
我使用 C++ shell 用 C++14 编译代码。
#include <iostream>
#include <type_traits>
using namespace std;
class A; // forward declaration.
template <typename T>
struct is_A : false_type {};
template <> struct is_A<A> : true_type {};
template <typename T>
struct is_int : false_type {};
template <> struct is_int<int> : true_type {};
template <> struct is_int<long> : true_type {};
class A{
public:
int val;
void print(void){
std::cout << val << std::endl;
}
template <typename T1>
enable_if_t<is_int<T1>::value,void>
operator=(const T1 & input){
val = 2*input; //Overload I
}
template <typename T1>
enable_if_t<is_A<T1>::value,void>
operator=(const T1 & Bb){
val = 5*Bb.val; //Overload II
}
};
int main(void){
A Aa;
A Bb;
int in_a = 3;
Aa = in_a; //This uses overload I as intended.
Bb = Aa; //I want this to use overload II, but
//actually overload I is used.
//This leads to an error during compilation.
Aa.print(); //This should give 6. (3x2)
Bb.print(); //This should give 30. (6x5)
}
【问题讨论】:
-
你有
operator=(A & Bb)没有T1...但是在你的情况下,简单的重载似乎就足够了。 -
operator =应该返回A&并采用 const 引用。 -
这是固定的(希望是正确的)。但是现在编译器又报错了。
-
enable_if也应该是enable_if_t。
标签: c++ c++14 template-specialization typetraits