替换失败并非错误

替换失败并非错误 (Substitution failure is not an error, SFINAE)是指C++语言在模板参数匹配失败时不认为这是一个编译错误。最先引入SFINAE缩写描述相关编程技术。

具体说,当创建一个重载函数的候选集时,某些(或全部)候选函数是用模板实参替换(可能的推导)模板形参的模板实例化结果。如果某个模板的实参替换时失败,编译器将在候选集中删除该模板,而不是当作一个编译错误从而中断编译过程,这需要C++语言标准授予如此处理的许可。 如果一个或多个候选保留下来,那么函数重载的解析就是成功的,函数调用也是良好的。

例子
下属简单例子解释了SFINAE:

struct Test {
typedef int foo;
};

template
void f(typename T::foo) {} // Definition #1

template
void f(T) {} // Definition #2

int main() {
f(10); // Call #1.
f(10); // Call #2. 并无编译错误(即使没有 int::foo)
// thanks to SFINAE.
}

在限定名字解析时(T::foo)使用非类的数据类型,导致f推导失败因为int并无嵌套数据类型foo, 但程序仍是良好定义的,因为候选函数集中还有一个有效的函数。

虽然SFINAE最初引入时是用于避免在不相关模板声明可见时(如通过包含头文件)产生不良程序。许多程序员后来发现这种行为可用于编译时内省(introspection)。具体说,在模板实例化时允许模板确定模板参数的特定性质。

例如,SFINAE用于确定一个类型是否包含特定typedef:

#include

template
struct has_typedef_foobar {
// Types "yes" and "no" are guaranteed to have different sizes,
// specifically sizeof(yes) == 1 and sizeof(no) == 2.
typedef char yes[1];
typedef char no[2];

template
static yes& test(typename C::foobar*);

template
static no& test(...);

// If the "sizeof" of the result of calling test(nullptr) is equal to
// sizeof(yes), the first overload worked and T has a nested type named
// foobar.
static const bool value = sizeof(test(nullptr)) == sizeof(yes);
};

struct foo {
typedef float foobar;
};

int main() {
std::cout ::value ::value

当类型T有嵌套类型foobar,test的第一个定义被实例化并且空指针常量被作为参数传入。(结果类型是yes。)如果不能匹配嵌套类型foobar,唯一可用函数是第二个test定义,且表达式的结果类型为no。省略号(ellipsis)不仅用于接收任何类型,它的转换的优先级是最低的,因而优先匹配第一个定义,这去除了二义性。

C++11的简化
C++11中,上述代码可以简化为:

#include
#include

template
using void_t = void;

template
struct has_typedef_foobar : std::false_type {};

template
struct has_typedef_foobar> : std::true_type {};

struct foo {
using foobar = float;
};

int main() {
std::cout ::value ::value

C++标准的未来版本中[https://en.cppreference.com/w/cpp/experimental/lib_extensions_2 Library fundamental v2 (n4562)] 建议把上述代码改写为:

#include
#include

template
using has_typedef_foobar_t = typename T::foobar;

struct foo {
using foobar = float;
};

int main() {
std::cout ::value ::value

Boost的使用者在boost::enable_if中使用SFINAE。

参考文献

评论 (0)

  • 还没有评论,来抢沙发吧。