c++ - 函数参数类型

标签 c++ templates template-meta-programming

我的代码应该是确定给定函数是否将给定类型作为参数。回答你 future 的“what for”问题我将很快回答:将它与 boost::enable_if 模板一起使用。

该代码使用了 C++11 的 decltype 运算符。我的问题是:是否可以使用 c++03 实现相同的目标?

#include <iostream>

template <class F, class P>
struct has_arg_of_type
{
    static bool const value = false;
};

template <class R, class A>
struct has_arg_of_type<R (A), A>
{
    static bool const value = true;
};

template <class R, class T, class A>
struct has_arg_of_type<R (T::*)(A), A>
{
    static bool const value = true;
};

int pisz(int);

class MyClass
{
public:
    void pisz(int);
};

int main(int argc, char *argv[])
{

    std::cout << "MyClass::pisz has the int as an argument? " << has_arg_of_type<decltype(&MyClass::pisz), int>::value << std::endl; // Line 32
    std::cout << "pisz has the int as an argument? ? " << has_arg_of_type<decltype(pisz), int>::value << std::endl;
    std::cout << "pisz has the float as an argument? ? " << has_arg_of_type<decltype(pisz), float>::value << std::endl;

    return 0;

}

错误是:

In function 'int main(int, char**)':
Line 32: error: 'MyClass::pisz(int)' cannot appear in a constant-expression

最佳答案

我想你可以通过 Boost.FunctionTypes 来做到这一点,或者您也可以使用提升类型特征。

#include <iostream>
#include <boost/function_types/function_type.hpp>
#include <boost/function_types/parameter_types.hpp>
#include <boost/typeof/std/utility.hpp>

float pisz(int);

class MyClass
{
public:
    void pisz(int);
};

int main(int argc, char *argv[])
{
    typedef BOOST_TYPEOF(&MyClass::pisz) MyClassPisz;
    typedef BOOST_TYPEOF(pisz) Pisz;

    typedef boost::mpl::at_c<boost::function_types::parameter_types<MyClassPisz>, 1>::type MemberFunction;
    typedef boost::mpl::at_c<boost::function_types::parameter_types<Pisz>, 0>::type Function;

    std::cout << "MyClass::pisz has the int as an argument? " << boost::is_same<MemberFunction, int>::value << std::endl;
    std::cout << "pisz has the int as an argument? ? " << boost::is_same<Function, int>::value << std::endl;
    std::cout << "pisz has the float as an argument? ? " << boost::is_same<Function, float>::value << std::endl;

    return 0;
}

关于c++ - 函数参数类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15644611/

相关文章:

c++ - 如何使用 Sublime Text 2 编译 gtkmm/gtk 程序

c++ - 读取较大文件时出现未处理的异常

c++ - 专门化 hashmap 模板

c++ - 基于方法的特化模板

c++ - 是否可以找出多态 C++ 14 lambda 的参数类型和返回类型?

c++ - 检查是否存在嵌套类型别名并有条件地设置类型别名

c++ - 为什么我不能在 C++ 中从该类的实例调用我的类的构造函数?

android - 无法使用 android ndk 使图像变灰

templates - 转到模板 : looping over index

c++ - 将 std::bind 的结果传递给 std::function "overloads"