Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/163.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ C+中的部分专用模板实例化+;忽略编译时错误_C++_Templates_Compile Time - Fatal编程技术网

C++ C+中的部分专用模板实例化+;忽略编译时错误

C++ C+中的部分专用模板实例化+;忽略编译时错误,c++,templates,compile-time,C++,Templates,Compile Time,下面的代码编译(并运行)很好,尽管我希望它会产生编译时错误: #include <iostream> using namespace std; template <typename T> struct is_int { static const bool value = false; }; template<> struct is_int<int> { static const bool value = true; }; /

下面的代码编译(并运行)很好,尽管我希望它会产生编译时错误:

#include <iostream>

using namespace std;

template <typename T>
struct is_int {
    static const bool value = false;
};

template<>
struct is_int<int> {
    static const bool value = true;
};

// General template definition with default second type parameter (void)
template <typename A, typename B = void>
struct Foo {
    static const int i = 42;
};

// Partially specialized template definition with possibly
// undefined second parameter
template<typename A>
struct Foo<A, typename enable_if<is_int<A>::value>::type > {
    static const int i = 56;
};


int main() {
    cout << Foo<bool>::i << endl; // Outputs '42'
    cout << Foo<int>::i << endl; // Outputs '56'
    return 0;
}
#包括
使用名称空间std;
模板
结构是完整的{
静态常量布尔值=假;
};
模板
结构是完整的{
静态常量布尔值=真;
};
//具有默认第二个类型参数(void)的常规模板定义
模板
结构Foo{
静态常数int i=42;
};
//部分专用化的模板定义,可能包含
//未定义的第二个参数
模板
结构Foo

那么,当
main
函数的第一行实例化template
Foo
时,编译器具体做什么?显然,当它试图匹配部分专门化时,它会遇到错误(因为未定义
type


它只是为了避免错误而放弃这个选择吗?

你所经历的是模板内省的基础,它被称为模板内省

简单地说:当模板参数替换失败时,它不会抛出,而是简单地“继续”并抓取下一个不会导致推断失败的候选项。这对于进行编译时分析非常有用


C++中没有局部模板特化/实例化这样的东西!?听起来你说的是“SFINAE”行为,它应该是@πάνταῥεῖ: 更正了(希望)标题。当前的标准也有。我们应该放弃这种行为,将c++03作为标记“成为标准”的等价物!(顺便说一句,OP中没有提到升压)@πάνταῥεῖ 有时候,记得事情从哪里来是件好事;)