比方说,我有这些模板别名:替换失败是否存在依赖于非类型模板参数的错误?
enum class enabler {};
template <typename T>
using EnableIf = typename std::enable_if<T::value, enabler>::type;
template <typename T>
using DisableIf = typename std::enable_if<!T::value, enabler>::type;
我可以做GCC如下:
#include <iostream>
template <typename T, EnableIf<std::is_polymorphic<T>> = {}>
void f(T) { std::cout << "is polymorphic\n"; }
template <typename T, DisableIf<std::is_polymorphic<T>> = {}>
void f(T) { std::cout << "is not polymorphic\n"; }
struct foo { virtual void g() {} };
int main() {
f(foo {});
f(int {});
}
它打印:
是多态的
并不多态
这符合我的期望。
随着铿锵的代码不编译。它会产生以下错误消息。
test.cpp:11:58: error: expected expression
template <typename T, EnableIf<std::is_polymorphic<T>> = {}>
^
test.cpp:14:59: error: expected expression
template <typename T, DisableIf<std::is_polymorphic<T>> = {}>
^
test.cpp:20:3: error: no matching function for call to 'f'
f(foo {});
^
test.cpp:12:6: note: candidate template ignored: couldn't infer template argument ''
void f(T) { std::cout << "is polymorphic\n"; }
^
test.cpp:15:6: note: candidate template ignored: couldn't infer template argument ''
void f(T) { std::cout << "is not polymorphic\n"; }
^
test.cpp:21:3: error: no matching function for call to 'f'
f(int {});
^
test.cpp:12:6: note: candidate template ignored: couldn't infer template argument ''
void f(T) { std::cout << "is polymorphic\n"; }
^
test.cpp:15:6: note: candidate template ignored: couldn't infer template argument ''
void f(T) { std::cout << "is not polymorphic\n"; }
^
4 errors generated.
它应该编译?这两个编译器中哪一个有问题?
哎呀,我觉得很傻。我有一种感觉,这与模板别名无关,所以标题可能会引起误解:S对不起,我会调查一下并修正标题,如果事实证明这种情况。 – 2012-04-16 19:48:45
'DisableIf> = {}'是否是合法的初始化程序列表初始化?结构可以是模板值参数吗? –
jpalecek
2012-04-16 19:49:34
@jpalecek不,结构不能。这就是为什么我使用枚举:) – 2012-04-16 19:51:17