Zebrafish
Zebrafish

Reputation: 14320

Can I get these template arguments deduced?

I left out the template parameters where the question marks were and I got an error, for obvious reason, but what to do in this case? I essentially want the two parameter arguments < ? , ? > to be the types of the getter and setter.

template <typename TGet, typename TSet>
class Object
{public:
    Object(int i, float f, TGet getter, TSet setter, const char* name) {}
};




class Creator
{public:
    template <typename T, typename ... TArgs>
    static T* create(int i, float f, TArgs ... args)
    {
        return new Object(i, f, args...);
    }

};

int main()
{
    Creator::create<Object< ? , ? >>(
        7,
        0.f,
        []() { return "Called Getter"; },
        [](const char* i) { std::cout << "Called Setter"; },
        "Name");
    
}

Also, I noted both my functions can become functions pointers, what if they were lambdas? What would go in the angled brackets < > ?

Upvotes: 0

Views: 35

Answers (1)

Andreas DM
Andreas DM

Reputation: 11018

Let the compiler deduce the types for you:

template <typename ... TArgs> // removed 'typename T'
static auto create(int i, float f, TArgs ... args)
{ //   ^^^^
    return new Object(i, f, args...);
}

And

Creator::create(
    7,
    0.f,
    []() { return "Called Getter"; },
    [](const char* i) { std::cout << "Called Setter"; },
    "Name");

godbolt link

Upvotes: 2

Related Questions