相关疑难解决方法(0)

如果在演绎期间无法解析函数的地址,是SFINAE还是编译器错误?

在C++ 0x中,简化了SFINAE规则,使得在演绎的"直接上下文"中出现的任何无效表达式或类型不会导致编译器错误,而是导致演绎失败(SFINAE).

我的问题是:
如果我采用重载函数的地址并且无法解决,那么在演绎的直接上下文中是否会失败?
(如果它无法解决,那么它是一个硬错误还是SFINAE)?

以下是一些示例代码:

struct X
{
  // template<class T> T* foo(T,T); // lets not over-complicate things for now
  void foo(char);
  void foo(int);
};


template<class U> struct S
{
  template<int> struct size_map 
  { typedef int type; };


// here is where we take the address of a possibly overloaded function
  template<class T> void f(T, 
      typename size_map<sizeof(&U::foo)>::type* = 0); 


  void f(...);
};

int main()
{
  S<X> s;

// should this cause a compiler error because 'auto T = &X::foo' …
Run Code Online (Sandbox Code Playgroud)

c++ templates sfinae overload-resolution c++11

23
推荐指数
1
解决办法
1万
查看次数

我可以在成员函数上使用boost :: enable_if吗?

我正在编写模板类,我想允许另一种方法仅存在于某种模板类型.目前,该方法适用于所有模板类型,但会导致所有其他类型的编译错误.

使这更复杂的是它是一个重载的operator().不知道我想要做什么实际上是可能的.

这就是我现在拥有的:

template<typename T, typename BASE>
class MyClass  : public BASE
{
public:

    typename T& operator() (const Utility1<BASE>& foo);
    typename T const& operator() (const Utility2<BASE>& foo) const;
};
Run Code Online (Sandbox Code Playgroud)

我希望T&版本始终可用,但T const&只有Utility2<BASE>有效版本才可用.现在,两种方法都存在,但如果Utility2<BASE>无效,尝试使用const版本会产生奇怪的编译错误.我宁愿有一个明智的错误,甚至是"没有这样的成员函数"错误.

这可能吗?

编辑:阅读了升级文档,这是我提出的,它似乎工作:

template<typename T, typename BASE>
class MyClass  : public BASE
{
public:

    typename T& operator() (const Utility1<BASE>& foo);

    template<typename U>
    typename boost::enable_if<boost::is_same<Utility2<BASE>, U>, T>::type const &
    operator() (const U& foo) const;
};
Run Code Online (Sandbox Code Playgroud)

因此,除非有人试图将它与Utility2一起使用,否则它不存在,并且如果它对该BASE类型有效,则它们只能创建一个Utility2.但是当它对BASE类型无效时,MyClass不会浪费时间创建访问器方法.

c++ templates boost enable-if

7
推荐指数
1
解决办法
3908
查看次数

通过使用traits使用模板类在编译时抛出错误来禁用函数

我有一个类,让我们Foo用几种方法调用它:

template<typename T>
class Foo {
public:
   Foo()               { /* ... */ }
   bool do_something() { /* ... */ }

   // This method should be callable only if:
   // std::is_floating_point<T>::value == true
   void bar() { 
      // Do stuff that is impossible with integer
   }
};
Run Code Online (Sandbox Code Playgroud)

我希望能够构建既Foo<double>Foo<int>,但我不希望允许调用bar()当类型T不是一个浮点类型.我还希望在编译时生成错误,而不是在运行时生成错误.所以,我想要的是:

Foo<double> a;
a.bar();                        // OK
Foo<int> b;
bool res = b.do_something();    // OK
b.bar();                        // WRONG: compile error
Run Code Online (Sandbox Code Playgroud)

我尝试了很多事情enable_if(与像帖子这个这一个),但我不能再使用的int …

c++ traits c++11 template-classes

3
推荐指数
1
解决办法
737
查看次数