函数声明中的static_assert

Pup*_*ppy 5 templates static-assert generic-programming visual-studio-2010 c++11

我有一个非常简单的功能使用static_assert.麻烦的是我想要static_assert在函数声明中涉及的行为 - 特别是推断返回类型.似乎没有任何地方可以插入,static_assert以便我可以在编译器无法推断出返回类型之前触发它.

到目前为止,我将返回类型推导和静态断言放在结构中.这将触发断言,这很好,但它仍然会在类型推导上产生错误,这是我想要消除的噪音.

#include <type_traits>
#include <functional>
#include <memory>
#include <map>
#include <iostream>
#include <string>
#include <cstdio>
#include <tuple>
#include <sstream>
#include <vector>
#include <algorithm>

template<typename T, typename X> struct is_addable {
    template<typename Test, typename Test2> static char test(decltype(*static_cast<Test*>(nullptr) + *static_cast<Test2*>(nullptr))*);
    template<typename Test, typename Test2> static int test(...);
    static const bool value = std::is_same<char, decltype(test<T, X>(nullptr))>::value;
};
template<typename T, typename X> struct is_addable_fail {
    static const bool value = is_addable<T, X>::value;
    static_assert(value, "Must be addable!");
    typedef decltype(*static_cast<T*>(nullptr) + *static_cast<X*>(nullptr)) lvalue_type;
};

template<typename T1, typename T2> auto Add(T1&& t1, T2&& t2) -> typename is_addable_fail<T1, T2>::lvalue_type {
    return std::forward<T1>(t1) + std::forward<T2>(t2);
}

struct f {};

int main() {
    std::cout << Add(std::string("Hello"), std::string(" world!"));
    Add(f(), f());
}
Run Code Online (Sandbox Code Playgroud)

Pet*_*der 0

由于候选集的构建方式和 SFINAE,这是不可能的。如果您可以在函数签名完全确定之前进行断言,那么就需要您在确定该函数是要使用的函数之前进行断言。

步骤的顺序基本上是:

  • 查找匹配的函数
  • 将推导的参数替换为函数参数和返回类型。
  • 丢弃那些失败的(SFINAE)
  • 如果还剩下一个,就用它。

您希望什么时候触发断言?

如果您在参数替换期间触发它,那么您就排除了 SFINAE,如果您在此之后的任何时间触发它,那么返回类型已经确定(为时已晚)。