简体   繁体   中英

C++ syntactic sugar or technique for prototype generation when using template specialization

I wonder what is the preferred C++ way for the generation of method prototypes,
when using template specialization? The technique I'm after
should scale well with the number of the foo class methods, see below.

The marked block of the reproducer has to be replaced.
Please no code snippets managed by hand or by a script.
Some additional small modifications (perhaps in the header) might be possible.

For brevity the templated class A is placed beside the typedef for Aint.

CRTP solutions are disfavored. Usage of C++17 (not later) is allowed.
Has to compile with VS2019 recent g++ and clang++.

Edit 2020-02-09:
Removing the marked block all together,
this compiles fine with Compiler Explorer's x64 MSVC 19.14 compiler.
So do we have a compiler issue here for g++ and clang++?

// begin of testspec.h
template<class T>
class A
{
public:
    A();
    void foo1();
    void foo2();
    void foo3();
};

typedef A<int> Aint;
// end of testspec.h

// begin of testspec.cpp
#include "testspec.h"

#include <iostream>

/////////////// can this block be simplified? //////////
template<>
void
A<int>::foo1();

template<>
void
A<int>::foo2();

template<>
void
A<int>::foo3();
/////////////// can this block be simplified? //////////

template<>
A<int>::A()
{
    foo1();
    foo2();
    foo3();
    std::cout << "hello world" << std::endl;
}

template<>
void
A<int>::foo1()
{
    std::cout << "foo1" << std::endl;
}

template<>
void
A<int>::foo2()
{
    std::cout << "foo2" << std::endl;
}

template<>
void
A<int>::foo3()
{
    std::cout << "foo3" << std::endl;
}
// end of testspec.cpp

// begin of main.cpp
#include "testspec.h"

int main()
{
    Aint a;
    return 0;
};
// end of main.cpp

Assuming that there is a part of A that does not get specialized, then the portion of A that you are trying to allow for modifiable behavior via specialization can be accomplished by adopting a policy pattern .

class APolicy {
    template <class, class> friend class A;
    void foo1 ();
    void foo2 ();
    void foo3 ();
};

template <class T, class P = APolicy>
class A {
    void foo1() { P().foo1(); }
    void foo2() { P().foo1(); }
    void foo3() { P().foo1(); }
};

And then instead of specializing A<int> , you implement a policy IntPolicy , and then instantiate A<int, IntPolicy> .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM