Lion
Lion

Reputation: 1035

How to restrict template arguments in C++?

I have two classes.

class Item {
};

template <typename ItemType>
class Result {
};

I want to implement a template, which should accept Item and Result< Item> as its template arguments(or something like int and Result< int>). If the arguments don't meet the requirements, errors should be reported during the compilation process.

What I've done:

template <typename ItemType, typename Result>
class Unknown {
 public:
  Result GetItem() {
    Result result;
    return result;
  }
};

My problem is that when other types are passed as arguments, no errors are reported.

// OK
Unknown<Item, Result<Item>> unknown;
Result<Item> result = unknown.GetItem();

// OK
Unknown<Item, SomeOtherResultTemplate<Item>> unknown10;
SomeOtherResultTemplate<Item> result = unknown10.GetItem();

// OK
Unknown<int, Result<int>> unknown;

// Errors should be reported.
Unknown<Item, int> unknown1;
Unknown<Item, Result<int>> unknown2;
Unknown<Item, Result<SomeOtherItem>> unknown3;
Unknown<int, Result<double>> unknown4;

Upvotes: 1

Views: 196

Answers (1)

R Sahu
R Sahu

Reputation: 206727

You can change Unknown to:

template <typename ItemType>
class Unknown {
 public:
  Result<ItemType> GetItem() {
    Result<ItemType> result;
    return result;
  }
};

and change it's usage to:

Unknown<Item> unknown;
Result<Item> result = unknown.GetItem();

Upvotes: 4

Related Questions