在 c++14 中,如果表达式格式不正确*,则 std::result_of 应该导致 SFINAE。相反,我在下面的最后一个案例中得到了一个编译错误(“二进制表达式的无效操作数”)(即让编译器推断 std::plus<> 的类型)。前三个案例按预期工作。代码和结果如下所示。
#include <boost/mpl/placeholders.hpp>
#include <boost/mpl/apply.hpp>
#include <iostream>
#include <utility>
#include <stdexcept>
#include <functional>
namespace mpl = boost::mpl;
template <typename OP, typename T, typename OP_T = typename mpl::apply<OP, T>::type>
struct apply_if_ok: OP_T {
template <typename...Args, typename R = std::result_of_t<OP_T(Args...)>>
R operator()(Args&&...args) const {
return static_cast<OP_T>(*this)(std::forward<Args>(args)...);
}
template <typename...Args>
auto operator()(...) const {
// throw std::runtime_error("Invalid arguments");
return "Invalid arguments";
}
};
int main() {
using OP = std::plus<mpl::_>;
int i = 3;
auto n1 = apply_if_ok<OP, void>()(1, 2);
std::cout << "plus (1, 2) = " << n1 << std::endl;
auto n2 = apply_if_ok<OP, void>()(1, &i);
std::cout << "plus (1, *) = " << n2 << std::endl;
auto n3 = apply_if_ok<OP, int>()(&i, &i);
std::cout << "plus (*, *) = " << n3 << std::endl;
// auto n4 = apply_if_ok<OP, void>()(&i, &i);
// std::cout << "plus (*, *) = " << n4 << std::endl;
}
输出:
% c++ -std=c++1y -g -pedantic sfinae_result_of.cc -o sfinae_result_of
./sfinae_result_of
plus (1, 2) = 3
plus (1, *) = 0x7fff5e782a80
plus (*, *) = Invalid arguments
% c++ -v
Apple LLVM version 6.0 (clang-600.0.56) (based on LLVM 3.5svn)
Target: x86_64-apple-darwin14.1.0
Thread model: posix
任何关于我做错了什么的指示将不胜感激!
谢谢。
- 来自cppreference.com。我认为相关的标准参考是 20.10.7.6,对最后一个表条目的评论。