【发布时间】:2015-01-19 21:03:47
【问题描述】:
我正在尝试过滤传递给重载函数模板的类型的方法。我正在使用 Visual Studio 2013。
三部分题:
- 为什么我的编译器不能推断出
Blorg3? -
TFoo2(argc)产生编译器错误的原因与#1 相同吗? - 有没有办法将模板参数传递给构造函数?
这里是示例代码:
#include <type_traits>
#define IFPTR(T,R) typename std::enable_if<std::is_pointer<T>::value, R>::type
#define IFINT(T,R) typename std::enable_if<std::is_integral<T>::value, R>::type
template <class T, IFINT(T, T)* = nullptr> int Blorg1(T n) { return n + 1; }
template <class T, IFPTR(T, T)* = nullptr> int Blorg1(T n) { return *n + 1; }
template <class T> IFINT(T, int) Blorg2(T n) { return n + 1; }
template <class T> IFPTR(T, int) Blorg2(T n) { return *n + 1; }
template <class T> int Blorg3(IFINT(T, T) n) { return n + 1; }
template <class T> int Blorg3(IFPTR(T, T) n) { return *n + 1; }
struct TFoo1 {
template <class T, IFINT(T, T)* _ = nullptr> TFoo1(T n) { }
};
struct TFoo2 {
template <class T> TFoo2(IFINT(T, T) n) { }
};
int main(int argc, char* argv[])
{
Blorg1(argc); // intellisense not happy
Blorg2(argc);
Blorg3<int>(argc); // why cant deduce?
Blorg1(*argv); // intellisense not happy
Blorg2(*argv);
Blorg3<char*>(*argv); // why cant deduce?
(void)TFoo1(argc); // intellisense not happy
(void)TFoo2(argc); // intellisense not happy and !!wont compile!!
return 0;
}
【问题讨论】:
-
1.因为模板参数只出现在 nested-name-specifier 中,这是一个非推导上下文(即导致模板参数不能从该特定参数的参数中推导) 2. 是 3.没有
标签: c++ templates c++11 sfinae template-argument-deduction