相关疑难解决方法(0)

使用指针非类型模板参数?

有没有人曾经使用指针/引用/指向成员(非类型)模板参数?
我不知道任何(理智/真实世界)场景,其中C++特性应该被用作最佳实践.

演示功能(用于指针):

template <int* Pointer> struct SomeStruct {};
int someGlobal = 5;
SomeStruct<&someGlobal> someStruct; // legal c++ code, what's the use?
Run Code Online (Sandbox Code Playgroud)

任何启蒙都将不胜感激!

c++ templates

15
推荐指数
2
解决办法
2734
查看次数

指向(数据)成员作为非类型模板参数的指针,例如具有自动存储持续时间/无链接

考虑以下片段:

#include <cstdint>
#include <iostream>

struct Foo {
    Foo() : foo_(0U), bar_(0U) {}

    void increaseFoo() { increaseCounter<&Foo::foo_>(); }
    void increaseBar() { increaseCounter<&Foo::bar_>(); }

    template <uint8_t Foo::*counter>
    void increaseCounter() { ++(this->*counter); }

    uint8_t foo_;
    uint8_t bar_;
};

void callMeWhenever() {
    Foo f;  // automatic storage duration, no linkage.
    f.increaseFoo();
    f.increaseFoo();
    f.increaseBar();

    std::cout << +f.foo_ << " " << +f.bar_;  // 2 1
}

int main() {
    callMeWhenever();
}
Run Code Online (Sandbox Code Playgroud)

我的第一个猜测会一直说这是病态的,因为fcallMeWhenever()具有自动存储时间,它的地址是不是在编译时已知,而成员模板函数increaseCounter()Foo与指针的数据成员实例化Foo,以及存储表示给定类类型的特定于编译器(例如填充)。但是,从cppreference / …

c++ templates pointer-to-member

5
推荐指数
1
解决办法
106
查看次数

将指向类的成员传递为模板参数

我想编写一个将进程应用于类成员的函数.以下代码正在运行:

class AA
{
public:
    AA(){};
    ~AA(){};
    std::string type="AA";
};

class BB
{
public:
    BB(){};
    ~BB(){};
    template <typename T, typename TT>
    void test(T& a, TT(T::*memberPtr))
    {
        std::cout<<"test: "<<(a.*memberPtr)<<std::endl;
    }
    std::string type="BB";
};

int main()
{
    AA a;
    BB b;
    b.test(a, &AA::type);
}
Run Code Online (Sandbox Code Playgroud)

但是我在编译时知道所有内容所以我想知道是否有可能写一些等价但只有模板?所以我可以这样写:

b.test<&AA::type>(a);
Run Code Online (Sandbox Code Playgroud)

调用内部测试(a):

std::cout<<"test: "<< (a.*MEMBER) <<std::endl; // MEMBER is given in template
Run Code Online (Sandbox Code Playgroud)

或类似的东西.

c++ templates

4
推荐指数
1
解决办法
1687
查看次数

标签 统计

c++ ×3

templates ×3

pointer-to-member ×1