Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-mvc/15.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++_Templates_Boost_Operator Overloading - Fatal编程技术网

C++ 如果在具有不同返回类型的重载运算符上启用_

C++ 如果在具有不同返回类型的重载运算符上启用_,c++,templates,boost,operator-overloading,C++,Templates,Boost,Operator Overloading,在这里,我尝试同时做3件事:使用模板重载赋值操作符,限制类型(使用boost::enable_if),以及使用特定的返回类型 以此为例: template <class T> std::string operator =(T t) { return "some string"; } 模板 字符串运算符=(T T){返回“某个字符串”;} 现在,根据boost(第3节,bullet pt 1),我必须使用enable_if作为返回类型,因为我重载了一个只能接受一个参数的运算符。但

在这里,我尝试同时做3件事:使用模板重载赋值操作符,限制类型(使用boost::enable_if),以及使用特定的返回类型

以此为例:

template <class T>
std::string operator =(T t) {  return "some string"; }
模板
字符串运算符=(T T){返回“某个字符串”;}
现在,根据boost(第3节,bullet pt 1),我必须使用enable_if作为返回类型,因为我重载了一个只能接受一个参数的运算符。但是,我希望返回类型是字符串,因此它不一定与模板参数的类型相同

我想使用enable_if仅仅是因为我想让它跳过模板,如果它不是一个有效的类型(而不是抛出错误)

有人对如何实现这一点有想法吗?

#包括
#include <iostream>
#include <boost/utility/enable_if.hpp>
#include <boost/mpl/vector.hpp>
#include <boost/mpl/contains.hpp>

class FooBar
{
public:
    FooBar () {}
    ~FooBar () {}

    template <typename T>
    typename boost::enable_if <
        typename boost::mpl::contains <
            boost::mpl::vector<std::string, int>, T>::type,
            std::string>::type
    operator = (T v)
    {
        return "some string";
    }
};

int
main ()
{
    FooBar bar;
    bar = 1;
    bar = std::string ("foo");
    // bar = "bar"; // This will give a compilation error because we have enabled
                    // our operator only for std::string and int types.
}
#包括 #包括 #包括 福巴级 { 公众: FooBar(){} ~FooBar(){} 模板 typename boost::如果< typename boost::mpl::contains< boost::mpl::vector,T>::type, std::string>::类型 运算符=(tV) { 返回“somestring”; } }; int 主要() { FooBar酒吧; bar=1; bar=std::字符串(“foo”); //bar=“bar”//这将导致编译错误,因为我们已启用 //我们的运算符仅适用于std::string和int类型。 }
将您实际需要的类型(在本例中为std::string)传递到enable_中。很好,这是boost库功能强大的一个很好的例子。非常感谢。