相关疑难解决方法(0)

指向非法参考成员的指针?

我们说我有:

// This is all valid in C++11.
struct Foo {
    int i = 42;
    int& j = i;
};

// Let's take a pointer to the member "j".
auto b = &Foo::j; // Compiler is not happy here
// Note that if I tried to get a pointer to member "i", it would work, as expected.
Foo f;
std::cout << f.*b; // Try using the pointer to member
Run Code Online (Sandbox Code Playgroud)

编译器抱怨我不能获取成员的地址,因为它是一个引用.确切地说:

语义问题:无法形成指向成员的指针指向成员'j'的引用类型'int&'

我知道这样做似乎毫无意义,但我只是想知道为什么不能这样做.

为什么这不可能?

c++ pointer-to-member language-lawyer

19
推荐指数
3
解决办法
4051
查看次数

类型特征:检查类是否具有特定功能(可能是继承)

我知道有很多可能的方法可以检测一个类是否具有特定的功能但是它们的确不适用于我的确切情况.除了继承函数之外,我当前检查正确成员函数的实现是否有效.

#include <type_traits>

template<typename T>                                                                
class HasFoo {                                                                                 
    template <typename U, int (U::*)(float)>                                  
      struct Check;                                                                 

    template <typename U>                                                       
      static std::true_type Test(Check<U, &U::foo> *);                 

    template <typename U>                                                           
      static std::false_type Test(...);                                               

public:
    static constexpr bool value = decltype(Test<T>(0))::value;                    
};

struct A {
  int foo(float);
};

struct B : public A {
};

struct C {
  unsigned int foo(double);
};

struct D {
  static int foo(float);
};

static_assert(HasFoo<A>::value, "A should have foo.");
static_assert(HasFoo<B>::value, "B should inherit foo from A.");

static_assert(!HasFoo<C>::value, "C should not …
Run Code Online (Sandbox Code Playgroud)

c++ type-traits c++11

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