Search code examples
c++templatesparametersreferencenon-type

C++ non-type template template parameters, reference to *this


I'm trying to improve my generic architecture, and I've decided that a system that uses this type of ambiguous context referencing would be ideal for my purposes. However, I'm having trouble figuring out how to get the syntax to work. I don't even know if something like this is possible! I have slightly shiestier alternatives that accomplish mostly the same thing but this would be best:

class IContained
{
public:
    virtual int getInt() = 0;
};
typedef std::shared_ptr<IContained>IContainedPtr;

template<template<class RefType, RefType& itsRef> class ContainedType>
class TestClass
{
    TestClass() :
        myContained(new ContainedType < TestClass, *this>())
    {

    }

    int getContextInt()
    {
        return 3;
    }

    IContainedPtr myContained;
};

template<class RefType, RefType& itsRef>
class Contained:
    virtual public IContained
{

    int getInt()
    {
        return itsRef.getContextInt();
    }
};

TEST(POTATO, PARTY)
{
    TestClass<Contained> myTest();

    int thing = myTest.myContained->getInt();

    EXPECT_EQ(thing, 3);
}

Solution

  • I am not sure what do you want to implement but I can explain why you are not able to use

    *this
    

    as template argument. Templates provide you with compile-time polymorphism. It means that all templates arguments should be known at compile time.

    this
    

    is a class instance variable, is an address of class instance, so it could not be determined during compilation. The same as

    *this